<template>
  <div class="simple-keyboard-container">
    <div class="simple-keyboard" ref="keyboardRef"></div>
    <!-- 隐藏的输入框用于捕获真实键盘事件 -->
    <input 
      ref="hiddenInput"
      class="hidden-input"
      type="text"
      autocomplete="off"
      readonly
      @keydown="handlePhysicalKeydown"
      @blur="refocusInput"
    />
  </div>
</template>

<script setup lang="ts">
import Keyboard from "simple-keyboard";
import "simple-keyboard/build/css/index.css";
import { ref, onMounted, watch, defineProps, defineEmits, nextTick } from "vue";

interface Props {
  currentKey?: string; // 当前需要按的键
  pressedKeys?: string[]; // 已经按过的键
  isActive?: boolean; // 是否激活状态
}

const props = withDefaults(defineProps<Props>(), {
  currentKey: '',
  pressedKeys: () => [],
  isActive: false
});

const emit = defineEmits<{
  keyPress: [key: string];
}>();

const keyboard = ref<Keyboard | null>(null);
const keyboardRef = ref<HTMLElement>();
const hiddenInput = ref<HTMLInputElement>();

const handleChange = (input: string) => {
  console.log("Input changed", input);
};

const handleKeyPress = (button: string) => {
  console.log("Virtual keyboard button pressed", button);
  const key = normalizeKey(button);
  emit('keyPress', key);
};

// 处理物理键盘按键
const handlePhysicalKeydown = (event: KeyboardEvent) => {
  console.log("Physical key pressed", event.key);
  const key = normalizeKey(event.key);
  emit('keyPress', key);
  event.preventDefault(); // 防止默认行为
};

// 标准化按键名称
const normalizeKey = (key: string): string => {
  const keyMap: Record<string, string> = {
    'w': 'W',
    'a': 'A', 
    's': 'S',
    'd': 'D',
    'W': 'W',
    'A': 'A',
    'S': 'S',
    'D': 'D'
  };
  return keyMap[key] || key.toUpperCase();
};

// 重新聚焦隐藏输入框
const refocusInput = () => {
  if (props.isActive && hiddenInput.value) {
    nextTick(() => {
      hiddenInput.value?.focus();
      console.log('隐藏输入框重新获取焦点');
    });
  }
};

onMounted(() => {
  if (!keyboardRef.value) return;
  
  keyboard.value = new Keyboard(keyboardRef.value, {
    onChange: handleChange,
    onKeyPress: handleKeyPress,
    layout: {
      'default': [
        '` 1 2 3 4 5 6 7 8 9 0 - = {bksp}',
        '{tab} q w e r t y u i o p [ ] \\',
        '{lock} a s d f g h j k l ; \' {enter}',
        '{shift} z x c v b n m , . / {shift}',
        '.com @ {space}'
      ]
    },
    display: {
      '{bksp}': '⌫',
      '{tab}': '⇥',
      '{lock}': '⇪',
      '{enter}': '↵',
      '{shift}': '⇧',
      '{space}': ' '
    }
  });
  
  updateKeyboardTheme();
  
  // 如果组件激活状态，立即获取焦点
  if (props.isActive) {
    nextTick(() => {
      hiddenInput.value?.focus();
      console.log('键盘组件已激活，隐藏输入框已获取焦点');
    });
  }
});

// 更新键盘主题
const updateKeyboardTheme = () => {
  if (!keyboard.value) return;
  
  const buttonTheme = [];
  
  // 当前需要按的键高亮
  if (props.currentKey && props.isActive) {
    buttonTheme.push({
      class: "hg-highlight",
      buttons: props.currentKey.toLowerCase()
    });
  }
  
  // 已按过的键变灰
  if (props.pressedKeys.length > 0) {
    buttonTheme.push({
      class: "hg-pressed",
      buttons: props.pressedKeys.map(k => k.toLowerCase()).join(' ')
    });
  }
  
  keyboard.value.setOptions({
    buttonTheme
  });
};

// 监听props变化，更新键盘主题和焦点
watch([() => props.currentKey, () => props.pressedKeys, () => props.isActive], () => {
  updateKeyboardTheme();
  
  // 当激活状态改变时，管理输入框焦点
  if (props.isActive) {
    nextTick(() => {
      hiddenInput.value?.focus();
      console.log('键盘激活，隐藏输入框获取焦点');
    });
  } else {
    hiddenInput.value?.blur();
    console.log('键盘取消激活，隐藏输入框失去焦点');
  }
}, { deep: true });
</script>

<style scoped>
.simple-keyboard-container {
  position: relative;
  max-width: 850px;
}

.simple-keyboard {
  max-width: 850px;
}

.hidden-input {
  position: absolute;
  top: -9999px;
  left: -9999px;
  width: 1px;
  height: 1px;
  opacity: 0;
  border: none;
  outline: none;
  background: transparent;
}

/* 自定义键盘样式 */
:global(.hg-highlight) {
  background: #3b82f6 !important;
  color: white !important;
  border: 2px solid #1d4ed8 !important;
  animation: pulse 1.5s infinite;
  box-shadow: 0 0 10px rgba(59, 130, 246, 0.5) !important;
}

:global(.hg-pressed) {
  background: #9ca3af !important;
  color: #6b7280 !important;
  border: 1px solid #9ca3af !important;
  opacity: 0.7;
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.7);
  }
  50% {
    transform: scale(1.05);
    box-shadow: 0 0 0 10px rgba(59, 130, 246, 0);
  }
}

/* 让键盘按钮有更好的视觉效果 */
:global(.hg-button) {
  transition: all 0.2s ease;
}

:global(.hg-button:hover) {
  background: #f3f4f6 !important;
}

:global(.hg-button:active) {
  transform: scale(0.95);
}
</style>
